package lab2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Map;

public class ReceiveACK extends Thread {
    private final DatagramSocket socket;
    private final Map<Integer, Integer> ackMap;

    public ReceiveACK(DatagramSocket socket, Map<Integer, Integer> ackMap) {
        this.socket = socket;
        this.ackMap = ackMap;
    }

    @Override
    public void run() {
        int end = 1;
        do {
            byte[] ackByte = new byte[Configuration.maxACKByteNumber + 1];//分配ACK报文长度大小的空间，最后一字节表示报文是否结束
            DatagramPacket packet = new DatagramPacket(ackByte, ackByte.length);//构造报文
            try {
                socket.receive(packet); //接收ACK报文
            } catch (IOException e) {
                System.out.println("");//忽略
                return;
            }
            int ack = 0xff & ackByte[0]; //获取ack序号
            if ((0xff & ackByte[1]) == 0) //判断报文是否结束
                end = 0;
            if (ackMap.get(ack) != null) {//如果收到的ack在之前没有出现，则将新的ack加入
                ackMap.put(ack, 1);
            }
            System.out.println("收到ack：" + ack);
        } while (end != 0 || ackMap.size() != 0);
        //当数据全部到达且全部收到ack时停止
    }
}
